package control

import (
	"database/sql"
	"errors"
	"strings"

	"crossrun.top/model"
)

//列出全部文章, pageNum form 1
func ListBlog(pageNum int, pageSize int) ([]model.Blog, error) {
	if pageNum < 1 {
		pageNum = 1
	}
	//查询数据
	rows, err := db.Query("SELECT * FROM blog ORDER BY modification DESC Limit ? offset ? ", pageSize, pageSize*(pageNum-1))
	defer rows.Close()
	return processBlog(rows), err
}

//根据文章分类列出全部文章, pageNum form 1
func ListBlogByCat(cid string, pageNum int, pageSize int) ([]model.Blog, error) {
	if pageNum < 1 {
		pageNum = 1
	}
	//查询数据
	rows, err := db.Query("SELECT * FROM blog where cid= ? Limit ? offset ?", cid, pageSize, pageSize*(pageNum-1))
	defer rows.Close()
	return processBlog(rows), err
}

//查询总行数
func ListBlogTotalSize(pageSize int, cid string) (t int, err error) {
	var rows *sql.Rows
	if cid == "" {
		rows, err = db.Query("select count(*) from blog ")
	} else {
		rows, err = db.Query("select count(*) from blog where cid = ?", cid)
	}

	defer rows.Close()
	rows.Next()
	total := 1
	rows.Scan(&total)
	if total%pageSize == 0 {
		t = total / pageSize
	} else {
		t = total/pageSize + 1
	}
	return
}

//通过ID查找文章
func ListBlogById(id string) model.Blog {
	//查询数据
	rows, err := db.Query("SELECT * FROM blog where id = ?", id)
	defer rows.Close()
	checkErr(err)
	blogs := processBlog(rows)
	if len(blogs) > 0 {
		return blogs[0]
	} else {
		return model.Blog{}
	}
}

//添加一篇文章
func AddBlog(blog model.Blog) error {
	if blog.Cata.Id == "" {
		return errors.New("分类不能为空")
	}

	var s string
	if len(blog.Tags) > 0 {
		s = "INSERT INTO blog(cid, content, title,time,modification,tags) values(?,?,?,?,?,?)"
	} else {
		s = "INSERT INTO blog(cid, content, title,time,modification,tags) values(?,?,?,?,?,?)"
	}

	//插入数据
	stmt, err := db.Prepare(s)
	if err != nil {
		return err
	}

	var res sql.Result

	if len(blog.Tags) > 0 {
		tags := blog.Tags[0].Id
		for i := 1; i < len(blog.Tags); i++ {
			tags = tags + "," + blog.Tags[i].Id + ","
		}
		res, err = stmt.Exec(blog.Cata.Id, blog.Content, blog.Title, blog.Time, blog.Modification, tags)
	} else {
		res, err = stmt.Exec(blog.Cata.Id, blog.Content, blog.Title, blog.Time, blog.Modification, "")
	}

	if err != nil {
		return err
	}

	_, err = res.LastInsertId()
	if err != nil {
		return err
	}

	return nil

}

//修改一篇文章
func UpdateBlog(blog model.Blog) error {

	if blog.Id == "" {
		return errors.New("文章ID不能为空")
	}

	s := "update blog set cid=? , content=? , title=? , modification=?,tags=? where id = ?"

	stmt, err := db.Prepare(s)
	if err != nil {
		return err
	}

	var res sql.Result
	tags := ""
	if len(blog.Tags) > 0 {
		tags = blog.Tags[0].Id
		for i := 1; i < len(blog.Tags); i++ {
			tags = tags + "," + blog.Tags[i].Id + ","
		}
	}

	res, err = stmt.Exec(blog.Cata.Id, blog.Content, blog.Title, blog.Modification, tags, blog.Id)

	if err != nil {
		return err
	}

	_, err = res.LastInsertId()
	if err != nil {
		return err
	}

	return nil

}

func processBlog(rows *sql.Rows) []model.Blog {
	var blogs []model.Blog
	for rows.Next() {
		var blog model.Blog
		var cid, tag string
		rows.Scan(&cid, &blog.Content, &blog.Title, &blog.Time, &blog.Modification, &tag, &blog.Id)

		if tag != "" {
			t := strings.Split(tag, ",")
			for _, ts := range t {
				if ts != "" {
					blog.Tags = append(blog.Tags, model.Tag{ts, "-1"})
				}
			}
		}

		cat := FindCataLogById(cid)
		if len(cat) > 0 {
			blog.Cata = cat[0]
		}
		blogs = append(blogs, blog)
	}

	return blogs

}
